/**
 * SSP for Web
 * Copyright 2013 Baidu Inc. All rights reserved.
 *
 * @file 验证信息清除扩展
 * @author otakustay
 */
define(
    function (require) {
        var InputControl = require('esui/InputControl');
        var TextBox = require('esui/TextBox');
        var Extension = require('esui/Extension');
        var main = require('esui/main');

        var exports = {};

        exports.type = 'ValidationCleaner';

        /**
         * 激活扩展
         *
         * @override
         */
        exports.activate = function () {
            var target = this.target;
            // 暂时只对`InputControl`控件生效
            if (!(target instanceof InputControl)) {
                return;
            }

            // 针对 TextBox 暂时先按 ue 的设计，在focus时机下做错误信息和提示文案的切换处理
            // 其他表单控件暂时先按 change 时机走，等待 ue 给出方案后再根据方案更改
            var type = target instanceof TextBox ? 'focus' : 'change';
            target.on(type, clean);
            this.$super(arguments);
        };

        /**
         * 取消扩展的激活状态
         *
         * @override
         */
        exports.inactivate = function () {
            var target = this.target;
            // 只对`InputControl`控件生效
            if (!(target instanceof InputControl)) {
                return;
            }

            var type = target instanceof TextBox ? 'focus' : 'change';
            target.un(type, clean);
            this.$super(arguments);
        };

        function clean() {
            if (this.validity) {
                // 移除这个 state，字段描述文案通过  state-invalid 控制隐藏与展示
                this.removeState('validity-' + this.validity.getValidState());
                var label = this.getValidityLabel(true);
                label.set('validity', null);
                this.validity = null;
            }
        }

        var ValidationCleaner = require('eoo').create(Extension, exports);
        main.registerExtension(ValidationCleaner);

        return ValidationCleaner;
    }
);
